#include "wifi_manager.h"
#include "esp_log.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "freertos/event_groups.h"
#include "lwip/err.h"
#include "lwip/sys.h"
#include "nvs_flash.h"

static const char *TAG = "WiFiManager";

// WiFi事件组
static EventGroupHandle_t s_wifi_event_group;
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

// WiFi配置
static char s_ssid[32] = {0};
static char s_password[64] = {0};
static wifi_status_t s_wifi_status = WIFI_DISCONNECTED;
static wifi_event_callback_t s_callback = NULL;
static char s_ip_address[16] = {0};
static char s_gw_address[16] = {0}; 
// WiFi事件处理
static void wifi_event_handler(void *arg, esp_event_base_t event_base, 
                              int32_t event_id, void *event_data)
{
    if (event_base == WIFI_EVENT) {
        switch (event_id) {
            case WIFI_EVENT_STA_START:
                ESP_LOGI(TAG, "WiFi station started");
                s_wifi_status = WIFI_CONNECTING;
                if (s_callback) s_callback(s_wifi_status);
                esp_wifi_connect();
                break;
                
            case WIFI_EVENT_STA_CONNECTED:
                ESP_LOGI(TAG, "Connected to AP");
                break;
                
            case WIFI_EVENT_STA_DISCONNECTED:
                ESP_LOGI(TAG, "Disconnected from AP");
                s_wifi_status = WIFI_DISCONNECTED;
                if (s_callback) s_callback(s_wifi_status);
                xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
                break;
                
            default:
                break;
        }
    } else if (event_base == IP_EVENT) {
        switch (event_id) {
            case IP_EVENT_STA_GOT_IP: {
                ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
                snprintf(s_ip_address, sizeof(s_ip_address), IPSTR, IP2STR(&event->ip_info.ip));
                
                // 获取网关IP
                const esp_netif_ip_info_t* ip_info = &event->ip_info;
                snprintf(s_gw_address, sizeof(s_gw_address), IPSTR, IP2STR(&ip_info->gw));  // 新增
                ESP_LOGI(TAG, "Got IP: %s", s_ip_address);
                ESP_LOGI(TAG, "Gateway IP: %s", s_gw_address);  // 新增打印网关IP
                
                s_wifi_status = WIFI_CONNECTED;
                if (s_callback) s_callback(s_wifi_status);
                xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
                break;
            }
                
            case IP_EVENT_STA_LOST_IP: {
                ESP_LOGI(TAG, "Lost IP address");
                s_ip_address[0] = '\0';
                s_gw_address[0] = '\0';  // 新增：清空网关IP
                break;
            }
        }
    }
}

void wifi_manager_init(const char *ssid, const char *password)
{
    // 初始化NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);
    
    // 创建事件组
    s_wifi_event_group = xEventGroupCreate();
    
    // 初始化TCP/IP适配器
    ESP_ERROR_CHECK(esp_netif_init());
    
    // 创建事件循环
    ESP_ERROR_CHECK(esp_event_loop_create_default());
    
    // 创建默认WiFi STA接口
    esp_netif_create_default_wifi_sta();
    
    // 初始化WiFi配置
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    
    // 注册事件处理
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_LOST_IP, &wifi_event_handler, NULL, NULL));
    
    // 保存SSID和密码
    strncpy(s_ssid, ssid, sizeof(s_ssid) - 1);
    strncpy(s_password, password, sizeof(s_password) - 1);
    
    // 设置WiFi模式
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    
    // 配置WiFi
    wifi_config_t wifi_config = {
        .sta = {
            .ssid = "",
            .password = "",
            .threshold.authmode = WIFI_AUTH_WPA2_PSK,
            .pmf_cfg = {
                .capable = true,
                .required = false
            },
        },
    };
    
    // 复制SSID和密码
    strncpy((char *)wifi_config.sta.ssid, s_ssid, sizeof(wifi_config.sta.ssid));
    strncpy((char *)wifi_config.sta.password, s_password, sizeof(wifi_config.sta.password));
    
    // 设置WiFi配置
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config));
    
    s_wifi_status = WIFI_DISCONNECTED;
    s_ip_address[0] = '\0';
}

void wifi_manager_start(void)
{
    if (s_wifi_status == WIFI_DISCONNECTED) {
        ESP_LOGI(TAG, "Starting WiFi connection to %s", s_ssid);
        s_wifi_status = WIFI_CONNECTING;
        if (s_callback) s_callback(s_wifi_status);
        
        ESP_ERROR_CHECK(esp_wifi_start());
        ESP_ERROR_CHECK(esp_wifi_connect());
    }
}

void wifi_manager_stop(void)
{
    if (s_wifi_status != WIFI_DISCONNECTED) {
        ESP_LOGI(TAG, "Stopping WiFi");
        ESP_ERROR_CHECK(esp_wifi_disconnect());
        ESP_ERROR_CHECK(esp_wifi_stop());
        s_wifi_status = WIFI_DISCONNECTED;
        if (s_callback) s_callback(s_wifi_status);
    }
}

wifi_status_t wifi_manager_get_status(void)
{
    return s_wifi_status;
}

void wifi_manager_register_callback(wifi_event_callback_t callback)
{
    s_callback = callback;
}

//获取本机IP地址
const char *wifi_manager_get_ip(void)
{
    return s_ip_address;
}

//获取网关IP
const char *wifi_manager_get_gw_ip(void)
{
    return s_gw_address;
}
